/*
 * @Author: WangLi
 * @Date: 2021-07-23 21:44:51
 * @LastEditors: WangLi
 * @LastEditTime: 2024-03-14 13:35:10
 * @Description:
 */
Component({
  externalClasses: ["custom-class", "custom-item-class", "custom-line-class"],
  options: {
    multipleSlots: true,
    addGlobalClass: true,
  },
  properties: {
    color: String,
    active: {
      type: String,
      value: "",
    },
    items: {
      type: Array,
      value: [],
    },
    lineWidth: {
      type: Number,
      value: 30,
    },
    lineHeight: {
      type: Number,
      value: 2,
    },
    duration: {
      type: Number,
      value: 0.3,
    },
    zIndex: {
      type: Number,
      value: 1,
    },
  },
  data: {
    lineOffsetLeft: 0,
  },
  ready() {
    this.init();
  },
  methods: {
    async init() {
      const index = this.data.items.findIndex((item) => item.value === this.data.active);
      const currentIndex = index === -1 ? 0 : index;
      const tabRef = await this.getTabRef();
      this.tabLeft = tabRef.left;
      const allTab = await this.getAllItemsRefs();
      this.tabWidths = allTab.map((tab) => tab.width);
      this.tabOffsets = allTab.map((tab) => tab.left);
      this.computedLineOffsetLeft(currentIndex);
    },
    getTabRef() {
      return new Promise((resolve) => {
        this.createSelectorQuery()
          .select(".s-tab")
          .boundingClientRect()
          .exec((rect = []) => {
            resolve(rect[0]);
          });
      });
    },
    getAllItemsRefs() {
      return new Promise((resolve) => {
        this.createSelectorQuery()
          .selectAll(".s-tab__item")
          .boundingClientRect()
          .exec((rect = []) => {
            resolve(rect[0]);
          });
      });
    },
    computedLineOffsetLeft(index) {
      const width = this.tabWidths[index];
      const offetLeft = this.tabOffsets[index];
      const lineOffsetLeft = width / 2 + offetLeft - this.tabLeft - this.data.lineWidth / 2;
      this.setData({
        lineOffsetLeft,
      });
    },
    onClick(e) {
      const value = e.currentTarget.dataset.value;
      if (value === this.data.active) {
        return;
      }
      // this.computedLineOffsetLeft(e.currentTarget.dataset.index);
      this.triggerEvent("change", { value });
    },
  },
});
